//
//  OrderDetailsViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/11/1.
//

import UIKit

class CarOrderDetailsViewController: BaseViewController {
    var tabelView: BaseTableView!
    var id = 0
    var dataArray = NSMutableArray()
    var infoModel: OrderInfoModel!
    var bgView: UIView!
    var gradient: CAGradientLayer!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("order_details", comment: "订单详情")
        self.setNavibarBgColor(bgColor: UIColor.init(hex: 0xffffff, alpha: 0))
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.view.backgroundColor = Theme.viewBkgGrayColor
        self.initTableView()
        self.initTabbar()
        self.view.bringSubview(toFront: self.navBar)
        self.requestGetProductOrderDetail()
    }
    
    // MARK: - Private
    func initTableView() {
        self.tabelView = BaseTableView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - NavBarHight), style: .plain)
        self.tabelView.backgroundColor = UIColor.clear
        self.tabelView.delegate = self
        self.tabelView.dataSource = self
        self.tabelView.separatorStyle = .none
        self.tabelView.rowHeight = UITableViewAutomaticDimension
        self.tabelView.register(CarOrderTableViewCell.self, forCellReuseIdentifier: "CarOrderTableViewCell")
        self.tabelView.register(CarOrderBasicInfoCell.self, forCellReuseIdentifier: "CarOrderBasicInfoCell")
        tabelView.showsVerticalScrollIndicator = false
        self.tabelView.estimatedRowHeight = 2
        self.view.addSubview(self.tabelView)
        
        let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: NavBarHight))
        header.backgroundColor = UIColor.clear
        tabelView.tableHeaderView = header
        
        let footer = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 100))
        footer.backgroundColor = UIColor.clear
        tabelView.tableFooterView = footer
        
        self.createBgLayer()
    }
    
    ///渐变色
    private func createBgLayer(){
        gradient = CAGradientLayer.init()
        gradient.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 124 + IphoneTopArea);//CAGradientLayer的控件大小
        let tempColorArray: [CGColor] = [UIColor.init(hex: 0xFED764, alpha: 1).cgColor, UIColor.init(hex: 0xFEFCF6, alpha: 0.27).cgColor]
        let locations: [NSNumber] = [0, 1]
        self.gradient?.colors = tempColorArray //渐变颜色
        self.gradient?.locations = locations //渐变起始位置
        self.gradient?.startPoint = CGPoint.init(x: 0, y: 0)
        self.gradient?.endPoint = CGPoint.init(x: 0, y: 1)
        self.view.layer.insertSublayer(gradient, at: 0)
    }
    
    func initTabbar(){
        
        self.bgView = UIView(frame: CGRect(x: 0, y: kScreenHeight - TabbarHeight, width: kScreenWidth, height: TabbarHeight))
        self.bgView.backgroundColor = .clear
        self.view.addSubview(self.bgView)
        self.bgView.isHidden = true
         
        let payBtn = UIButton(frame: CGRect(x: 14, y: 10, width: kScreenWidth - 28, height: 46))
        payBtn.backgroundColor = Theme.mainColor
        payBtn.layer.cornerRadius = 8
        payBtn.layer.masksToBounds = true
        payBtn.setTitleColor(.white, for: .normal)
        payBtn.setTitle(MMLocalizedString("pay_now", comment: "立即支付"), for: .normal)
        payBtn.titleLabel?.font = UIFont(name: Theme.PingFangSCMedium, size: 16)
        payBtn.addTarget(self, action: #selector(payBtnAntion), for: .touchUpInside)
        self.bgView.addSubview(payBtn)
        
        
        
    }
    
    
    //MARK: - Requset
    //订单详情
    func requestGetProductOrderDetail(){
        self.view.showLoadingHUDText(nil)
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.productOrderDetail(param: ["id": "\(self.id)"]), objectType: OrderInfoPreviewModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! OrderInfoPreviewModel
            if resultObj.code == "1" {
                self.infoModel = resultObj.data
                self.obligationDealData()
                
                //待付款时间到结束刷新数据
                self.infoModel?.refreshDataBlock = { [weak self] in
                    self?.requestGetProductOrderDetail()
                }                
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
            self.tabelView.reloadData()
        } error: { err in
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
        
    }
    
    
    //待付款处理
    func obligationDealData(){
       if self.infoModel?.status == 1{
           self.tabelView.frame.size.height = kScreenHeight - NavBarHight - TabbarHeight
           self.bgView.isHidden = false
       }else{
           self.tabelView.frame.size.height = kScreenHeight - NavBarHight
           self.bgView.isHidden = true
       }
        
    }
    
    
    
    //MARK: - Antion
    //立即支付
    @objc func payBtnAntion(){
        let tempOrder = OrderContentListModel()
        tempOrder.orderNo = self.infoModel?.orderNo ?? ""
        tempOrder.price = self.infoModel?.depositAmount ?? 0
        
        let vc = PaymentViewController()
        vc.orderContentModel = tempOrder
        vc.modalPresentationStyle = .overFullScreen
        self.present(vc, animated: false)
        
        
        vc.pushFirstDataBlock = {[weak self] urlStr in
            let vc = MyWebController()
            vc.urlStr = urlStr
            vc.titleStr = MMLocalizedString("confirm_first_pay", comment: "FirstData支付")
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        
        
    }

}

extension CarOrderDetailsViewController: UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
      return  UITableViewAutomaticDimension
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "CarOrderTableViewCell", for: indexPath) as! CarOrderTableViewCell
            if self.infoModel != nil {
                cell.setModel(model: self.infoModel)
            }
            return cell
        
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "CarOrderBasicInfoCell", for: indexPath) as! CarOrderBasicInfoCell
            if self.infoModel != nil {
                cell.setModel(model: self.infoModel)
            }
            return cell
        }
    
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        headerView.backgroundColor = .clear
        return headerView
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        return footerView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

extension CarOrderDetailsViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY: CGFloat = scrollView.contentOffset.y
        if offsetY > 100 {
            let alpha = offsetY / 100.0
            self.setNavibarBgColor(bgColor: UIColor.init(hex: 0xffffff, alpha: alpha))
        }else{
            self.setNavibarBgColor(bgColor: UIColor.init(hex: 0xffffff, alpha: 0))
        }
    }
}
